import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    nickName: '',
    avatar: '',
    deptId: '',
    userId: '',
    roles: [],
    permissions: [],
    message: 0,
    FeatureMessage: {},
    isCondition: '1',
    todayAspectFlag: '',
    logoMax: '',
    logomin: '',
    numObj: {},
    Phone: '',
    ruleList: JSON.parse(sessionStorage.getItem('ruleList'))
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_RULELIST: (state, ruleList) => {
      state.ruleList = ruleList
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_DEPT: (state, deptId) => {
      state.deptId = deptId
    },
    SET_USER: (state, userId) => {
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_MESSAGE: (state, message) => {
      state.message = message
    },
    SET_FEATUREMESSAGE: (state, FeatureMessage) => {
      FeatureMessage.upkeepTaskCount = 0
      FeatureMessage.upkeepAcceptanceCount = 0
      FeatureMessage.repairCount = 0
      let num = 0;
      for (const key in FeatureMessage) {
        const element = FeatureMessage[key];
        num += element
      }
      state.FeatureMessage = { ...FeatureMessage, num: num }
    },
    SET_ISCONDITION: (state, isCondition) => {
      state.isCondition = isCondition
    },
    SET_TODAYASPECTFLAG: (state, todayAspectFlag) => {
      state.todayAspectFlag = todayAspectFlag
    },
    SET_NUMOBJ: (state, numObj) => {
      state.numObj = numObj
    },
    SET_LOGOMAX: (state, logoMax) => {
      state.logoMax = logoMax
    },
    SET_LOGOMIN: (state, logoMin) => {
      state.logoMin = logoMin
    },
    SET_PHONE: (state, Phone) => {
      state.Phone = Phone
    },
  },
  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          console.log(res.data.access_token);
          setToken(res.data.access_token)
          commit('SET_TOKEN', res.data.access_token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.user
          const avatar = (user.avatar == "" || user.avatar == null) ? require("@/assets/images/profile.jpg") : user.avatar;
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_NAME', user.userName)
          commit('SET_NICKNAME', user.nickName)
          commit('SET_DEPT', user.deptId)
          commit('SET_USER', user.userId)
          commit('SET_LOGOMAX', user.dept.logoMax)
          commit('SET_LOGOMIN', user.dept.logoMin)
          commit('SET_AVATAR', avatar)
          commit('SET_PHONE', user.phonenumber)
          commit('SET_TODAYASPECTFLAG', user.todayAspectFlag)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          sessionStorage.removeItem("ruleList")
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
